package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.FreemarkUtil;
import cn.wolfcode.trip.base.domain.Goods;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.GoodsQueryObject;
import cn.wolfcode.trip.base.service.IGoodsService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Lyu
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {

    private final IGoodsService goodsService;
    private final ServletContext ctx;

    @Autowired
    public GoodsController(IGoodsService goodsService, ServletContext ctx) {
        this.goodsService = goodsService;
        this.ctx = ctx;
    }

    /**
     * 获取某个类型的商品
     */
    @GetMapping(value = "/{type}", produces = "text/html;charset=UTF-8")
    public void queryGoods(GoodsQueryObject qo, HttpServletResponse resp) throws Exception {
        String dir = ctx.getRealPath("/temp");
        Map<String, Object> map = new HashMap<>();
        map.put("id", qo.getType());
        // 全部数据
        qo.setPageSize(8);
        PageInfo<Goods> pageInfo = goodsService.queryForList(qo);
        // 如果是翻页操作则直接返回数据即可
        if (qo.getCurrentPage() != 1) {
            map.put("info", pageInfo);
            FreemarkUtil.witerDate(dir, "classify.ftl", map, resp.getWriter());
            return;
        }
        qo.setPageSize(0);
        List<Goods> commends = goodsService.queryForList(qo).getList();
        map.put("commends", commends);
        map.put("info", pageInfo);
        FreemarkUtil.witerDate(dir, "goodsContent.ftl", map, resp.getWriter());
    }

    /**
     * 查询所有商品
     *
     * @return 商品
     */
    @GetMapping
    public Object list() {
        return goodsService.listAll();
    }

    /**
     * 查询需要积分最高的商品
     */
    @GetMapping("/expensive")
    public Object getExpensive() {
        return goodsService.getExpensive();
    }

    /**
     * 根据id查询商品
     */
    @GetMapping("/{id}")
    public Object getGoods(@PathVariable Long id) {
        return goodsService.get(id);
    }
}
